from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework.response import Response
from .common_logger import logger


# 自定义异常类，内置DRF不够
class NoPermissionException(Exception):
    pass


def exception_handler(exc, context):
    # 记录日志
    request = context.get('request')
    view = context.get('view')
    ip = request.META.get('REMOTE_ADDR')
    path = request.get_full_path()
    method = request.method
    user_id = request.user.id or '[匿名用户]'

    logger.error(f'操作出错:{str(exc)},ip地址为:{ip},请求方式是:{method},请求地址是:{path},用户为:{user_id}'
                 f',视图类为:{str(view)}')
    res = drf_exception_handler(exc, context)
    if res:
        # drf异常
        if isinstance(res.data, dict):
            err = res.data.get('detail') or res.data.get('non_field_errors') or res.data or '系统错误'
            print(err)
        elif isinstance(res.data, list):
            err = res.data[0]
            print(err)
        else:
            err = "服务异常请稍后再试 -drf"
        response = Response({'code': 999, 'msg': err})
        # response = Response({'code': 9990, 'msg': exc.detail})
    else:
        # 更细粒度异常
        if isinstance(exc, ZeroDivisionError):
            err = "数据操作异常，除以0了"
            code = 909
        elif isinstance(exc, NoPermissionException):
            err = f"没有操作权限:{str(exc)}"
            code = 906
        else:
            err = f"{str(exc)}"
            code = 909
        response = Response({'code': code, 'msg': err})

    return response
